import {
  cancelPm,
  selectPmByPage,
  selectPmFormByPage,
  selectStageAndUserCount,
  startScore
} from '@/api/assessment'
import {CCard} from '@/components/card'
import AdjustScoreModal from '@/components/modal/adjustScoreModal'
import InitiationScoreModal, {InitiationScore} from '@/components/modal/initiatingScoreModal'
import {PMContent, PMLayout, PMNav} from '@/components/others/layout'
import {SplitLine} from '@/components/splitLine'
import {CnMediumP, CnMediumSpan, CnNormalP} from '@/components/text'
import {useLoading} from '@/hooks/loading'
import useModal from '@/hooks/modalHook'
import {useRouteQuery} from '@/hooks/pageRedirect'
import {useTableLoading, useTablePaging} from '@/hooks/tableHook'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {debounce, throttle} from '@/libs/debounce'
import {InitiateAssessmentCheckPageQuery, toInitiateAssessmentInfo} from '@/libs/pageRedirect'
import {getSession} from '@/libs/sessionStorage'
import { defineComponent, reactive, computed, watch, onMounted, onActivated } from 'vue'

export default defineComponent({
  name: 'initiateAssessmentCheck',
  setup(props, ctx) {
    const {route, router, getQueryData} = useRouteQuery({queryKeys: ['pmFormId']})
    let pageQuery = getQueryData<InitiateAssessmentCheckPageQuery>()
    if (!pageQuery) return () => <div></div>

    const defaultPmFormId = Number(pageQuery.pmFormId)

    const {store} = useGlobalAPI()

    const {page, changePage, size, getPagination, changeTableTotal} = useTablePaging({
      page: 1,
      size: 10
    })

    const {loading, startLoading, closeLoading} = useTableLoading()
    const {
      loading: pageLoading,
      startLoading: startPageLoading,
      closeLoading: closePageLoading
    } = useLoading()

    const {visible: initiationScoreVisible, openModal: openInitiationScoreModal} = useModal()

    const {
      visible: adjustScoreVisible,
      openModal: openAdjustScoreModal,
      modalValue: adjustScoreModalValue,
      setModalValue: setAdjustScoreModalValue
    } = useModal<number>()

    const cloumns: CColumn<PmForm.BaseInfoTableData>[] = [
      {
        title: '姓名',
        dataIndex: 'pmUserName'
      },
      {
        title: '部门',
        dataIndex: 'pmDeptName'
      },
      {
        title: '考评组',
        dataIndex: 'pmGroupName'
      },
      {
        title: '考核周期',
        dataIndex: 'pmPeriodName'
      },
      {
        title: '绩效等级',
        dataIndex: 'pmScoreLevel'
      },
      {
        title: '考核阶段',
        dataIndex: 'pmStageName',
        width: 160
      },
      {
        title: '状态',
        dataIndex: 'status'
      },
      {
        title: '操作',
        dataIndex: 'utils',
        width: 300
      }
    ]

    let state = reactive<{
      dataSource: PmForm.BaseInfoTableData[]
      stageAndUserCountList: PmForm.StageAndUserCount[]
      currentStageCode: PmGroupStageCode | undefined
      pmFormList: PmForm.TableData[]
      currentPmFormId: number | undefined

      pmUserName: string | undefined
      pmStatusCode: string | undefined
      pmPeriodCode: string | undefined
      pmStageCode: PmGroupStageCode | undefined
      pmScoreLevel: string | undefined
      pmDeptDDId: string | undefined

      initiationScoreVisible: boolean
    }>({
      dataSource: [],
      stageAndUserCountList: [],
      currentStageCode: undefined,
      pmFormList: [],
      currentPmFormId: undefined,

      pmUserName: undefined,
      pmStatusCode: undefined,
      pmPeriodCode: undefined,
      pmStageCode: undefined,
      pmScoreLevel: undefined,
      pmDeptDDId: undefined,

      initiationScoreVisible: false
    })

    const pmFormOptions = computed(() =>
      state.pmFormList.map(item => ({
        label: item.pmFormName,
        value: item.pmFormId
      }))
    )

    const loginUserInfo = computed(() => store.getters['dingding/ddUserInfo'])

    watch(
      () => state.currentStageCode,
      n => {
        getTableData()
      }
    )

    watch(
      () => state.currentPmFormId,
      n => {
        getTableData()
        getStageAndUserCount()
      }
    )

    function selectOptionFilter(input: string, option: {label: string; value: number}) {
      return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }

    function handleSendScoreBySelf(data: InitiationScore.Emits.ConfirmArg) {
      if (!state.currentPmFormId) return
      startScore({
        pmFormId: state.currentPmFormId,
        startUserDDId: loginUserInfo.value.userId,
        pmGroupIdList: data.pmGroupList.join(','),
        userDDList: data.pmGroupUserList.join(',')
      })
        .then(res => {
          getTableData()
        })
        .catch(err => {})
    }

    function getPmFormList() {
      startPageLoading()
      selectPmFormByPage({
        page: 1,
        size: 999999
      })
        .then(res => {
          state.pmFormList = res.data.list
          closePageLoading()
        })
        .catch(err => {
          closePageLoading()
        })
    }

    function getTableData() {
      if (!state.currentPmFormId) return
      startLoading()
      selectPmByPage({
        page: page.value,
        size: size.value,
        pmFormId: state.currentPmFormId,
        pmStageCode: state.currentStageCode,
        pmUserName: state.pmUserName
      })
        .then(res => {
          state.dataSource = res.data.list
          changeTableTotal(res.data.total)
          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })
    }

    const throttleGetTableData = throttle(() => {
      if (page.value !== 1) {
        changePage(1)
      }
      getTableData()
    }, 300)

    function getStageAndUserCount() {
      if (!state.currentPmFormId) return
      selectStageAndUserCount({
        pmFormId: state.currentPmFormId
      })
        .then(res => {
          state.stageAndUserCountList = res.data.sort((a, b) => a.sort - b.sort)
          state.currentStageCode = undefined
        })
        .catch(err => {})
    }

    function getPageData() {
      getPmFormList()
    }

    onMounted(() => {
      state.currentPmFormId = Number(defaultPmFormId)
      getPageData()
    })

    onActivated(() => {
      let pageQuery = getQueryData<InitiateAssessmentCheckPageQuery>()

      if (pageQuery?.isRefersh == 1) {
        state.pmUserName = ''
        state.currentPmFormId = Number(pageQuery.pmFormId)
        changePage(1)
        getPageData()
      }
    })
    return () => (
      <PMLayout spinning={pageLoading.value}>
        <PMNav
          v-slots={{
            title: () => (
              <div class='flex items-center gap-x-8'>
                <a-select
                  class='w-222'
                  v-model={[state.currentPmFormId, 'value']}
                  show-search
                  placeholder='请选择'
                  options={pmFormOptions.value}
                  filter-option={selectOptionFilter}
                  onChange={throttleGetTableData}
                ></a-select>
                <CnMediumSpan>内所有人员</CnMediumSpan>
              </div>
            )
          }}
          backClick={() => {
            router.push({name: 'assessmentInitiated'})
          }}
        ></PMNav>
        <PMContent>
          <CCard title='绩效考核-人员信息' showTitle={false} loading={loading.value}>
            <div class='flex items-center justify-between'>
              <div class='flex items-center gap-x-12'>
                <a-input
                  class='w-266 rounded-4'
                  placeholder='请输入姓名搜索'
                  v-slots={{
                    prefix: () => <i class='iconfont icon-fangdajing text-infoHalf text-13'></i>
                  }}
                  allowClear
                  v-model={[state.pmUserName, 'value']}
                  onInput={throttleGetTableData}
                ></a-input>
              </div>
              <div class='flex items-center gap-x-12'>
                <a-button
                  class='rounded-4 bg-primary text-white'
                  type='primary'
                  onClick={() => {
                  
                    
                    openInitiationScoreModal()
                  }}
                >
                  发起评分
                </a-button>
                {/* <a-button class='rounded-4'>一键催办</a-button> */}
              </div>
            </div>
            <div class='bg-infoLight border-1 border-cardLine h-44 rounded-4 my-24 flex items-center'>
              {state.stageAndUserCountList.map((item, idx) => {
                switch (item.stageName) {
                  case '全部':
                    return (
                      <div class='flex-1 h-full flex items-center justify-center relative'>
                        <CnMediumSpan
                          class={[
                            'cursor-pointer hover:text-primary',
                            state.currentStageCode === undefined ? 'text-primary' : ''
                          ]}
                          onClick={() => {
                            state.currentStageCode = undefined
                          }}
                        >
                          {item.stageName}
                          {` (${item.count})`}
                        </CnMediumSpan>
                        <SplitLine
                          class='absolute top-1/2 right-0 w-2 h-22 transform -translate-y-1/2 p-0'
                          style={{backgroundColor: '#afafaf'}}
                        ></SplitLine>
                      </div>
                    )
                  default:
                    return (
                      <div class='flex-1 h-full flex items-center justify-center relative'>
                        <CnMediumSpan
                          class={[
                            'cursor-pointer hover:text-primary',
                            state.currentStageCode === item.stageCode ? 'text-primary' : ''
                          ]}
                          onClick={() => {
                            state.currentStageCode = item.stageCode
                          }}
                        >
                          {item.stageName}
                          {` (${item.count})`}
                        </CnMediumSpan>
                        {idx === state.stageAndUserCountList.length - 1 ? null : (
                          <i
                            class='iconfont icon-youjiantou text-12 absolute top-1/2 right-0 transform -translate-y-1/2'
                            style={{
                              color: '#afafaf'
                            }}
                          ></i>
                        )}
                      </div>
                    )
                }
              })}
            </div>
            <a-table
              class='custom-table'
              columns={cloumns}
              pagination={getPagination({
                getTableData
              })}
              dataSource={state.dataSource}
              bordered
              loading={loading.value}
            >
              {{
                bodyCell: ({text, record, column, index}: CBodyCell<PmForm.BaseInfoTableData>) => {
                  switch (column.dataIndex) {
                    case 'status':
                      return record.status ? (
                        <CnNormalP
                          class='p-16 text-12 cursor-pointer '
                          onClick={() => {
                            record.status &&
                              toInitiateAssessmentInfo({
                                pmFormId: state.currentPmFormId,
                                userDDId: record.pmUserDDId,
                                title: '员工绩效详情',
                                defaultPmId: record.pmId,
                                groupId: record.pmGroupId,
                                type: 'checkInfo'
                              })
                          }}
                        >
                          正常
                        </CnNormalP>
                      ) : (
                        <CnNormalP
                          class='p-16 text-danger text-12 cursor-pointer '
                          onClick={() => {
                            record.status &&
                              toInitiateAssessmentInfo({
                                pmFormId: state.currentPmFormId,

                                userDDId: record.pmUserDDId,
                                title: '员工绩效详情',
                                defaultPmId: record.pmId,
                                groupId: record.pmGroupId,
                                type: 'checkInfo'
                              })
                          }}
                        >
                          已撤销
                        </CnNormalP>
                      )
                    case 'utils':
                      return record.status ? (
                        <div class='p-16 flex items-center gap-x-8'>
                          <CnMediumSpan
                            class='text-primary cursor-pointer text-12'
                            onClick={() => {
                              toInitiateAssessmentInfo({
                                pmFormId: state.currentPmFormId,

                                userDDId: record.pmUserDDId,
                                title: '员工绩效详情',
                                defaultPmId: record.pmId,
                                groupId: record.pmGroupId,
                                type: 'checkInfo'
                              })
                            }}
                          >
                            查看
                          </CnMediumSpan>

                          <CnMediumSpan
                            class='text-primary cursor-pointer text-12'
                            onClick={() => {
                              setAdjustScoreModalValue(record.pmId)
                              openAdjustScoreModal()
                            }}
                          >
                            调整考核结果
                          </CnMediumSpan>
                          <a-popconfirm
                            title={`确认撤销${record.pmUserName}的绩效`}
                            ok-text='确认'
                            cancel-text='取消'
                            onConfirm={() => {
                              let makeUserDDId = getSession('userDDId')
                              if (!makeUserDDId) return
                              cancelPm({
                                pmId: record.pmId,
                                makeUserDDId: makeUserDDId
                              })
                                .then(res => {
                                  getTableData()
                                })
                                .catch(err => {})
                            }}
                          >
                            <CnMediumSpan class='text-danger cursor-pointer text-12'>
                              撤销
                            </CnMediumSpan>
                          </a-popconfirm>
                        </div>
                      ) : (
                        <div
                          class='p-16 cursor-pointer '
                          onClick={() => {
                            record.status &&
                              toInitiateAssessmentInfo({
                                pmFormId: state.currentPmFormId,

                                userDDId: record.pmUserDDId,
                                title: '员工绩效详情',
                                defaultPmId: record.pmId,
                                groupId: record.pmGroupId,
                                type: 'checkInfo'
                              })
                          }}
                        ></div>
                      )
                    default:
                      return (
                        <CnNormalP
                          class='p-16 text-12 cursor-pointer'
                          onClick={() => {
                            record.status &&
                              toInitiateAssessmentInfo({
                                pmFormId: state.currentPmFormId,

                                userDDId: record.pmUserDDId,
                                title: '员工绩效详情',
                                defaultPmId: record.pmId,
                                groupId: record.pmGroupId,
                                type: 'checkInfo'
                              })
                          }}
                        >
                          {text}
                        </CnNormalP>
                      )
                  }
                }
              }}
            </a-table>
          </CCard>
        </PMContent>

        {state.currentPmFormId ? (
          <InitiationScoreModal
            v-model={[initiationScoreVisible.value, 'visible']}
            pmFormId={state.currentPmFormId}
            onConfirm={handleSendScoreBySelf}
          ></InitiationScoreModal>
        ) : null}

        <AdjustScoreModal
          v-model={[adjustScoreVisible.value, 'visible']}
          pmId={adjustScoreModalValue.value}
          onConfirm={() => {
            getTableData()
          }}
        ></AdjustScoreModal>
      </PMLayout>
    )
  }
})
